#include "modbusclient.h"
#include "QModbusRtuSerialMaster"
#include "QVariant"
#include "QSerialPort"
#include "QDebug"
ModbusClient::ModbusClient(QObject *parent) : QObject(parent)
{

    //Dr □ i1 i2 CR LF
    state=false;
    modbus=new QModbusRtuSerialMaster();
    QVariant serial("/dev/ttyAMA0");

    modbus->setConnectionParameter(QModbusDevice::SerialPortNameParameter,serial );
    modbus->setConnectionParameter(QModbusDevice::SerialBaudRateParameter,QSerialPort::Baud9600);
    modbus->setConnectionParameter(QModbusDevice::SerialDataBitsParameter,8);
    modbus->setConnectionParameter(QModbusDevice::SerialStopBitsParameter,1);
}
bool ModbusClient::start()
{
    state= modbus->connectDevice();
    return state;
}

bool ModbusClient::isconnect()
{
    return this->state;
}
void ModbusClient::sendaccess()
{
    //第二个字符1表示流路，之后是一个空格，然后1和2表示收信ID，CR和LF是回车换行
    QVector<quint16> value;
    value<<'D'<<'1'<<' '<<'1'<<'2'<<'CR'<<'LF';
    QModbusDataUnit readUnit(QModbusDataUnit::Coils, 0, value);

    if (auto *reply = modbus->sendReadRequest(readUnit, 0)) // client id 255
    {
        if (!reply->isFinished())
        {
            connect(reply, &QModbusReply::finished, this, &ModbusClient::readread);
        }
        else
        {
            delete reply; // broadcast replies return immediately
        }
    }
    else
    {
        // request error
    }
}
void ModbusClient::readread()
{
    //QModbusReply这个类存储了来自client的数据,sender()返回发送信号的对象的指针
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
    {
        return;
    }
    //数据从QModbusReply这个类的resuil方法中获取,也就是本程序中的reply->result()
    if (reply->error() == QModbusDevice::NoError)
    {
        const QModbusDataUnit unit = reply->result();
        for (uint i = 0; i < unit.valueCount(); i++)
        {
            const QString entry = tr("Address: %1, Value: %2").arg(unit.startAddress()).arg(QString::number(unit.value(i),
                                                                                                            unit.registerType() <= QModbusDataUnit::Coils ? 10 : 16));
            // ui->textEdit_2->append(entry);
        }
    }
    else if (reply->error() == QModbusDevice::ProtocolError)
    {
        qDebug()<<"Read response error:"+reply->errorString()+"Mobus exception: 0x"+reply->rawResult().exceptionCode();
    }
    else
    {
        qDebug()<<"Read response error:"+reply->errorString()+ "code:0x "+reply->error();
    }
    reply->deleteLater();
    emit senddata();
}
